package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.interceptors.LoginInterceptor;
import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.bean.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 新增购物车方法
     * 参数cart中只有浏览器传递的：skuId 和 count
     * @return
     */
    @GetMapping
    public String addCart(Cart cart){

        this.cartService.addCart(cart);
        // 重定向到成功的方法路径
        return "redirect:http://cart.gmall.com/addCart.html?skuId=" + cart.getSkuId() + "&count=" + cart.getCount();
    }

    /**
     * 新增成功方法，展示新增购物车成功页面
     * 参数cart中只有浏览器传递的：skuId 和 count
     * @param cart
     * @return
     */
    @GetMapping("addCart.html")
    public String queryCartBySkuId(Cart cart, Model model){
        BigDecimal count = cart.getCount();
        cart = this.cartService.queryCartBySkuId(cart.getSkuId());
        cart.setCount(count);
        model.addAttribute("cart", cart);
        return "addCart";
    }

    @PostMapping("updateNum")
    @ResponseBody
    public ResponseVo updateNum(@RequestBody Cart cart){
        this.cartService.updateNum(cart);
        return ResponseVo.ok();
    }

    @PostMapping("deleteCart")
    @ResponseBody
    public ResponseVo deleteCart(@RequestParam("skuId")Long skuId){
        this.cartService.deleteCart(skuId);
        return ResponseVo.ok();
    }

    /**
     * 只要根据userKey 或者userId查询就可以了，不需要任何参数
     * @return
     */
    @GetMapping("cart.html")
    public String queryCarts(Model model){
        List<Cart> carts = this.cartService.queryCarts();
        model.addAttribute("carts", carts);
        return "cart";
    }

    @GetMapping("user/{userId}")
    @ResponseBody
    public ResponseVo<List<Cart>> queryCheckedCartsByUserId(@PathVariable("userId")Long userId){
        List<Cart> carts = this.cartService.queryCheckedCartsByUserId(userId);
        return ResponseVo.ok(carts);
    }

    @GetMapping("test")
    @ResponseBody
    public String test(HttpServletRequest request){
        long now = System.currentTimeMillis();
        System.out.println("这是controller中的test方法开始执行");

        ListenableFuture<Void> future1 = this.cartService.execute1();
        Future<String> future2 = this.cartService.execute2();

        future1.addCallback(t -> {}, ex -> {
            System.out.println("executor1出现异常了，异常信息：" + ex.getMessage());
        });
        try {
            future1.get();
        } catch (Exception e) {
            System.out.println("executor1出现异常了，异常信息：" + e.getMessage());
        }

        try {
            future2.get();
        } catch (Exception e) {
            System.out.println("executor2出现异常了，异常信息：" + e.getMessage());
        }

//        ListenableFuture<String> future1 = this.cartService.execute1();
//        ListenableFuture<String> future2 = this.cartService.execute2();
//        future1.addCallback(t -> {
//            System.out.println("execute1执行成功，返回结果集：" + t);
//        }, ex -> {
//            System.out.println("execute1执行失败，失败原因：" + ex.getMessage());
//        });
//        future2.addCallback(t -> {
//            System.out.println("execute2执行成功，返回结果集：" + t);
//        }, ex -> {
//            System.out.println("execute2执行失败，失败原因：" + ex.getMessage());
//        });

//        try {
//            Future<String> future1 = this.cartService.execute1();
//            Future<String> future2 = this.cartService.execute2();
//            // get方法依然可以获取返回结果集，并捕获异常信息，但是不推荐
//            System.out.println("execute1的返回结果集：" + future1.get() + ", execute2方法的返回结果集：" + future2.get());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
        System.out.println("controller中的test方法执行完成" + (System.currentTimeMillis() - now));
        //System.out.println("============================test========" + LoginInterceptor.getUserInfo());
        return "hello test";
    }
}
